package log

import (
	"fmt"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"time"
)

func NewLog(conf Conf) (l *zerolog.Logger, e error) {
	level, err := zerolog.ParseLevel(conf.Level)
	if err != nil {
		e = err
		return
	}

	zerolog.TimeFieldFormat = time.DateTime

	lj := &lumberjack.Logger{
		Filename:   fmt.Sprintf("%s%s", conf.Path, conf.Name),
		MaxSize:    conf.MaxSize,
		MaxAge:     conf.MaxAge,
		MaxBackups: conf.MaxBackups,
		LocalTime:  conf.LocalTime,
		Compress:   false,
	}

	var logger zerolog.Logger
	if conf.Console {
		consoleWrite := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.DateTime}
		multi := zerolog.MultiLevelWriter(consoleWrite, lj)
		logger = log.With().Logger().Level(level).Output(multi)
	} else {
		logger = log.With().Logger().Level(level).Output(lj)
	}

	l = &logger

	return
}
